#!/bin/bash

# 设置变量
PROJECT_DIR=$(pwd)
DEPLOY_DIR="$PROJECT_DIR/deploy"
ZIP_FILE="$DEPLOY_DIR/deploy.zip"

# 创建部署目录
mkdir -p $DEPLOY_DIR

# 安装 AWS CLI
pip install awscli --upgrade --user

# 配置 AWS 凭证
aws configure

# 创建 Elastic Beanstalk 应用
aws elasticbeanstalk create-application \
    --application-name lock-express-baxk \
    --description "Smart Lock Express Backend"

# 创建 RDS 数据库实例
aws rds create-db-instance \
    --db-instance-identifier lock-express-db \
    --db-instance-class db.t2.micro \
    --engine mysql \
    --master-username admin \
    --master-user-password your_password \
    --allocated-storage 20 \
    --backup-retention-period 7

# 打包应用
echo "Building project..."
npm run build

echo "Creating deployment package..."
cd $PROJECT_DIR
zip -r $ZIP_FILE . \
    -x "node_modules/*" \
    -x ".git/*" \
    -x "*.log" \
    -x "deploy/*" \
    -x ".env*" \
    -x "*.zip"

echo "Deployment package created at: $ZIP_FILE"

# 创建 Elastic Beanstalk 环境
aws elasticbeanstalk create-environment \
    --application-name lock-express-baxk \
    --environment-name lock-express-env \
    --solution-stack-name "64bit Amazon Linux 2 v5.6.1 running Node.js 14" \
    --option-settings file://.ebextensions/nodecommand.config

# 部署应用
echo "Uploading deployment package to S3..."
aws elasticbeanstalk create-application-version \
    --application-name lock-express-baxk \
    --version-label v1 \
    --source-bundle S3Bucket=your-bucket,S3Key=deploy.zip

echo "Updating environment..."
aws elasticbeanstalk update-environment \
    --environment-name lock-express-env \
    --version-label v1

echo "Deployment completed!" 